﻿Public Module Mathematical
    REM 二分法
    Public Function SqrtDiv2(v As Single, Optional it As SByte = 16) As Single
        Dim f As Single = 0
        Dim t As Single = v
        Dim h As Single = 0
        For i = 0 To it - 1
            h = (t - f) * 0.5
            If (f + h) * (f + h) > v Then
                t = t - h
            Else
                f = f + h
            End If
            'Console.WriteLine("t={0},f={1}", t, f)
        Next
        Return (t + f) * 0.5
    End Function

    REM https://www.bilibili.com/video/BV1Nt411T7HT?from=search&seid=4026278962513637535
    REM X[n+1] =  X[n] - f(x[n]) / f'(x[n])
    REM 函数  y = x * x. 写成零点方程 0 = x * x - y
    REM 所以根号7: 7 = x * x   =>  0 =  x * x - 7 即f(x) = x * x - 7
    Public Function SqrtNewton(v As Single, Optional it As SByte = 16) As Single
        Dim xm As Single = v
        For i = 0 To it
            Dim xn As Single = xm - (xm * xm - v) / (2 * xm)
            'Console.WriteLine("xn={0}", xn)
            xm = xn
        Next
        Return xm
    End Function

    Public Function CubertNewton(v As Single, Optional it As Byte = 16) As Single
        Dim xm As Single = v
        For i = 0 To it - 1
            Dim xn As Single = xm - (xm * xm * xm - v) / (3 * xm * xm)
            Console.WriteLine("itr = {0}, xn={1}", i, xn)
            xm = xn
        Next
        Return xm
    End Function

End Module
